import React from 'react';
import store from './../Store';

export default class SumComponet extends React.Component {

    constructor(props) {
        super(props);
        this.state = this.getCountSum();
    }

    getCountSum = () => {
        const state = store.getState();
        let sum = 0;
        for (const key in state) {
            sum += state[key];
        }
        return { sum: sum };
    }

    onChange = () => {
        this.setState(this.getCountSum())
    }

    componentDidMount = () => {
        store.subscribe(this.onChange);
    }

    componentWillUnmount = () => {
        store.unsubscribe(this.onChange);
    }

    render() {
        return (
            <p>Total:{ this.state.sum }</p>
        )
    }
}